/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-11-25     86159       the first version
 */


#include"mutex.h"
void th3_entry(void *parameter)
{
    while(1)
    {
        rt_mutex_take(mutexx, RT_WAITING_FOREVER);//获取互斥量  上锁
        flag3++;
        rt_thread_mdelay(3000);//延时就休眠了
        flag4++;
        rt_mutex_release(mutexx);//释放互斥量  解锁
    }
}
void th4_entry(void *parameter)
{
    while(1)
    {
        rt_mutex_take(mutexx, RT_WAITING_FOREVER);//获取互斥量 上锁
        flag3++;
        flag4++;
        rt_mutex_release(mutexx);//释放互斥量  解锁
        rt_kprintf("flag3:%d,flag4:%d\n",flag3,flag4);
    }
}
int mutex(void)
{
    //动态创建互斥锁
    mutexx=rt_mutex_create("mutex1", RT_IPC_FLAG_FIFO);
    if(mutexx==RT_NULL)
    {
        LOG_E("mutex1 rt_mutex_create failed...\n");
        return -ENOMEM;
    }
    LOG_D("mutex1 rt_mutex_create successed...\n");

    //静态创建互斥锁
    /*
    int ret;
    ret=rt_mutex_init(&mutexx2, "mutex2", RT_IPC_FLAG_FIFO);
    if(ret<0)
    {
        LOG_E("mutex2 rt_mutex_init failed...\n");
        return ret;
    }
    LOG_D("mutex2 rt_mutex_init successed...\n");
    */
    /*
    rt_mutex_delete(mutex1);//删除动态互斥锁
    rt_mutex_detach(mutex2);//删除静态互斥锁
    */

    thh3=rt_thread_create("th3", th3_entry, RT_NULL, 512, 20, 5);
    if(thh3==RT_NULL)
    {
        LOG_E("th3 rt_thread_create failed...\n");
        return -ENOMEM;
    }
    thh4=rt_thread_create("th4", th4_entry, RT_NULL, 512, 20, 5);
    if(thh4==RT_NULL)
    {
        LOG_E("th4 rt_thread_create failed...\n");
        return -ENOMEM;
    }
    rt_thread_startup(thh3);//启动线程
    rt_thread_startup(thh4);
    return 0;
}
